package com.cloudcc.mobile.view.activity;

import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.utils.DistanceUtil;
import com.cloudcc.cloudframe.bus.BaseEvent;
import com.cloudcc.cloudframe.bus.DynamicEventList;
import com.cloudcc.cloudframe.bus.EventEngine;
import com.cloudcc.cloudframe.bus.IEventLife;
import com.cloudcc.mobile.AppContext;
import com.cloudcc.mobile.R;
import com.cloudcc.mobile.dao.BullXiangGuanDao;
import com.cloudcc.mobile.dao.impl.BullXiangGuanImpl;
import com.cloudcc.mobile.entity.AddImageInfo;
import com.cloudcc.mobile.entity.BullJxsNewJob;
import com.cloudcc.mobile.event.BeauEventList;
import com.cloudcc.mobile.manager.LocationManager;
import com.cloudcc.mobile.manager.RunTimeManager;
import com.cloudcc.mobile.manager.UserManager;
import com.cloudcc.mobile.presenter.DynamicControl;
import com.cloudcc.mobile.util.ImageUtil;
import com.cloudcc.mobile.util.Tools;
import com.cloudcc.mobile.util.photo.Constants;
import com.cloudcc.mobile.util.photo.Util;
import com.cloudcc.mobile.view.base.BaseActivity;
import com.mypage.adapter.CommonListAdapter;
import com.mypage.model.GongNiuData;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class BullXunjianActivity extends BaseActivity implements View.OnClickListener,IEventLife{
    private TextView jxs_bull,md_bull,tfdz_bull,zcbm_bull,zcmc_bull,zclx_bull,address_tv,zczt_bull_tv,bull_address_tv;
    private ImageView photo_1,photo_2,chatmes_menubtn,zczt_img;
    private EditText zcsl_bull,qkms_bull;
    private String imagename;
    private static final int TAKE_PHOTO_1 = 5001;
    private static final int TAKE_PHOTO_2 = 5002;
    private List<AddImageInfo> imageArray = new ArrayList<AddImageInfo>();
    private List<AddImageInfo> imageArray2 = new ArrayList<AddImageInfo>();
    private List<AddImageInfo> imageArrayAll = new ArrayList<AddImageInfo>();

    private ImageLoadingListener animateFirstListener = new Util.AnimateFirstDisplayListener();
    private String mEns = RunTimeManager.getInstance().getlanguage();
    private GongNiuData data;
    //图片上传
    private DynamicControl dynamicControl = new DynamicControl();
    private String mChange;

    private Map<String,String> jsonlist;
    private String jxsname;
    private Button save_xunjian;
    private CommonListAdapter mAdapter;

    private List<String> mListx;
    private List<BullJxsNewJob> listJxs, listMenD;
    private LatLng formlatLng;//起始经纬度
    private LatLng tolatLng;//目的地经纬度
    private boolean wubai = false;
    private String isxunjian = "yeah";
    private String caozuozb;
    private BullXiangGuanDao bullDao;
    private String jxsId;
    private String mdid;
    private String datax;
    private boolean isSave = false;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        register();
//        setContentView(R.layout.activity_bull_xunjian);
        bullDao = new BullXiangGuanImpl();
        initView();
        initdata();
        setDate();
        initLocation();
        jxsId = data.id;
        BeauEventList.BullMenDianEvent event = new BeauEventList.BullMenDianEvent();//查询门店

        bullDao.BullgetMenD("mendian", "dyjxs='" + jxsId + "'", "name,dzzb", event);

//        sendDate();
    }
    private void initLocation() {
        LocationManager.getInstance().registerListener(mListener);
        LocationManager.getInstance().requestLocal();
    }

    public void onEventMainThread(BeauEventList.BullMenDianEvent event) {

        listMenD = event.getData();
        if(listMenD.size() == 0 ) {
            return;
        }
        for (int i =0;i<listMenD.size()-1;i++){
            if(data.ssmendianccname.equals(listMenD.get(i).name)) {
                mdid = listMenD.get(i).name;
                return;
            }
        }

        if (listMenD != null && listMenD.size() != 0) {//查询到门店
        } else {//没有查到门店
        }
    }
    private void sendDate() {

        if ("en".equals(mEns)) {
            showWainting("Uploading image...");
        } else {
            showWainting("正在上传图片...");
        }
        if(imageArray.size()>0) {
            imageArrayAll.add(imageArray.get(0));
        }

        if(imageArray2.size()>0) {
            imageArrayAll.add(imageArray2.get(0));
        }
        if(imageArrayAll.size()<1) {
            Toast.makeText(BullXunjianActivity.this, "请至少传一张图片", Toast.LENGTH_SHORT).show();
            dismissWainting();
            return;
        }
        dynamicControl.sendPhotoBull(imageArrayAll, jsonlist,isxunjian);
    }
    public void onEventMainThread(DynamicEventList.SendDynamicEvent event) {
        dismissWainting();
        if (event.isError()) {
            if (event.getStatusCode() == BaseEvent.SC_LOGIN_INVAILED) {// 登录失效
                Intent intent = new Intent(mContext, BindActivity.class);
                mContext.startActivity(intent);
            } else if (event.getStatusCode() == BaseEvent.NET_NO_NETWORK) {// 没有网络
                if ("en".equals(mEns)) {

                    Tools.showInfo(mContext, "No network yet...");
                }else{
                    Tools.showInfo(mContext, "暂无网络...");
                }

            } else if(event.getMessage()!=null) {
              String rtunrninfo =   event.getMessage();
                Toast.makeText(BullXunjianActivity.this, rtunrninfo.substring(rtunrninfo.indexOf("：")+1,rtunrninfo.length()), Toast.LENGTH_LONG).show();
                
            }else {
                Toast.makeText(BullXunjianActivity.this, "保存失败", Toast.LENGTH_SHORT).show();

                finish();
            }
            return;
        }

        RunTimeManager.getInstance().setGongniu("xunjian");
        finish();

    }
    private void setDate() {
        jxs_bull.setText(jxsname);
        md_bull.setText(data.ssmendianccname);
        tfdz_bull.setText(data.tfdz);
        zcbm_bull.setText(data.name);
        zcmc_bull.setText(data.zcmc);
        zclx_bull.setText(data.zclx);
        zcsl_bull.setText(data.scsl);
//        jxs_bull.setText(data.dyjxs);
//        md_bull.setText(data.dymendian);
//        tfdz_bull.setText(data.czdd);
//        zcbm_bull.setText(data.dyjxs);
//        zcmc_bull.setText(data.);
    }

    private void initdata() {
        SimpleDateFormat sDateFormat    =   new    SimpleDateFormat("yyyy-MM-dd    HH:mm:ss");
        datax    =    sDateFormat.format(new    java.util.Date());
        data = (GongNiuData) getIntent().getSerializableExtra("gongniudata");
        jxsname = getIntent().getStringExtra("ssjxs");
    }


    private void initView() {
        //经销商
        jxs_bull = (TextView)findViewById(R.id.jxs_bull);
        //门店
        md_bull = (TextView)findViewById(R.id.md_bull);
        //投放地址
        tfdz_bull = (TextView)findViewById(R.id.tfdz_bull);
        //资产编码
        zcbm_bull = (TextView)findViewById(R.id.zcbm_bull);
        //资产名称
        zcmc_bull = (TextView)findViewById(R.id.zcmc_bull);
        //资产类型
        zclx_bull = (TextView)findViewById(R.id.zclx_bull);
        //地址
        address_tv = (TextView)findViewById(R.id.bull_address_tv);
        //资产状态
        zczt_bull_tv = (TextView)findViewById(R.id.zczt_bull_tv);
        //资产数量
        zcsl_bull = (EditText) findViewById(R.id.zcsl_bull);
        //照片1
        photo_1 = (ImageView)findViewById(R.id.photo_1);
        //照片2
        photo_2 = (ImageView)findViewById(R.id.photo_2);
        //情况描述
        qkms_bull = (EditText)findViewById(R.id.qkms_bull);
        //返回按钮
        chatmes_menubtn = (ImageView)findViewById(R.id.chatmes_menubtn);
        //保存
        save_xunjian = (Button)findViewById(R.id.save_xunjian);

        zczt_img = (ImageView)findViewById(R.id.zczt_img);
        //定位
        bull_address_tv = (TextView)findViewById(R.id.bull_address_tv);
        chatmes_menubtn.setOnClickListener(this);
        photo_1.setOnClickListener(this);
        photo_2.setOnClickListener(this);
        save_xunjian.setOnClickListener(this);
        zczt_img.setOnClickListener(this);
        zczt_bull_tv.setOnClickListener(this);

    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_bull_xunjian;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(requestCode == TAKE_PHOTO_1) {
            File f = new File(Environment.getExternalStorageDirectory()
                    + "/" + "CloudCC" + "/photo/" + imagename);
            try {
                Uri u = Uri.parse(MediaStore.Images.Media
                        .insertImage(getContentResolver(),
                                f.getAbsolutePath(), null, null));
                String imageurl = getAbsoluteImagePathx(u);
                AddImageInfo imageInfo = new AddImageInfo();
                imageInfo.setImagePath(shuiyin(imageurl));
                imageArray.add(imageInfo);
                setPhotos();
            } catch (FileNotFoundException e) {
                Tools.handle(e);
            }
        }else if(requestCode == TAKE_PHOTO_2) {
            File f = new File(Environment.getExternalStorageDirectory()
                    + "/" + "CloudCC" + "/photo/" + imagename);
            try {
                Uri u = Uri.parse(MediaStore.Images.Media
                        .insertImage(getContentResolver(),
                                f.getAbsolutePath(), null, null));
                String imageurl = getAbsoluteImagePathx(u);
                AddImageInfo imageInfo = new AddImageInfo();
                imageInfo.setImagePath(shuiyin(imageurl));
                imageArray2.add(imageInfo);
                setPhotos2();
            } catch (FileNotFoundException e) {
                Tools.handle(e);
            }
        }

        super.onActivityResult(requestCode, resultCode, data);
    }

    private void setPhotos2() {
        List<String> selectedImagePathArray = AppContext.selectPhotos;
        if (imageArray2.size() + selectedImagePathArray.size() > 9) {
            selectedImagePathArray.clear();
            if ("en".equals(mEns)) {
                Tools.showInfo(mContext, "Add up to 9 images");
            } else {
                Tools.showInfo(mContext, "最多添加9张图片");
            }

            return;
        }
        for (String imagePath : selectedImagePathArray) {
            if (imageArray2.contains(imagePath)) {// 去重
                continue;
            }
            AddImageInfo imageInfo = new AddImageInfo();

            imageInfo.setImagePath(imagePath);
            imageArray2.add(imageInfo);
        }
        AddImageInfo localImageInfo = imageArray2.get(0);
//        adapter = new AddmicroPostGridviewAdapter(mContext, imageArray);
//        containerGridViewPhoto.setAdapter(adapter);
//        setAdapterListener();
        ImageLoader.getInstance().displayImage("file://" + localImageInfo.getImagePath(), photo_2,
                Constants.IM_IMAGE_OPTIONS, animateFirstListener);
        selectedImagePathArray.clear();
    }

    /**
     * 设置选中的 图片
     */
    private void setPhotos() {
        List<String> selectedImagePathArray = AppContext.selectPhotos;
        if (imageArray.size() + selectedImagePathArray.size() > 9) {
            selectedImagePathArray.clear();
            if ("en".equals(mEns)) {
                Tools.showInfo(mContext, "Add up to 9 images");
            } else {
                Tools.showInfo(mContext, "最多添加9张图片");
            }

            return;
        }
        for (String imagePath : selectedImagePathArray) {
            if (imageArray.contains(imagePath)) {// 去重
                continue;
            }
            AddImageInfo imageInfo = new AddImageInfo();

             imageInfo.setImagePath(imagePath);
            imageArray.add(imageInfo);
        }
        AddImageInfo localImageInfo = imageArray.get(0);
//        adapter = new AddmicroPostGridviewAdapter(mContext, imageArray);
//        containerGridViewPhoto.setAdapter(adapter);
//        setAdapterListener();
        ImageLoader.getInstance().displayImage("file://" + localImageInfo.getImagePath(), photo_1,
                Constants.IM_IMAGE_OPTIONS, animateFirstListener);
        selectedImagePathArray.clear();
    }
    public String getAbsoluteImagePathx(Uri uri) {
        String[] proj = {MediaStore.Images.Media.DATA};
        @SuppressWarnings("deprecation")
        Cursor cursor = managedQuery(uri, proj, // Which columns to return
                null, // WHERE clause; which rows to return (all rows)
                null, // WHERE clause selection arguments (none)
                null); // Order-by clause (ascending by name)
        int column_index = cursor
                .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.photo_1:
                takePhoto(TAKE_PHOTO_1);
                break;
            case R.id.photo_2:
                takePhoto(TAKE_PHOTO_2);
                break;
            case R.id.chatmes_menubtn:
                finish();
                break;
            case R.id.save_xunjian:
//                if(wubai) {
//                   Toast.makeText(BullXunjianActivity.this, "与门店距离大于500米", Toast.LENGTH_SHORT).show();
//                    return;
//                }
                isSave = true;
                if(TextUtils.isEmpty(zcsl_bull.getText().toString())) {
                    Toast.makeText(BullXunjianActivity.this, "资产数量不能为空", Toast.LENGTH_SHORT).show();
                    return;
                }
                showWainting("正在定位");
                initLocation();


                break;
            case R.id.zczt_bull_tv:
                showPopupWindow(zczt_img);
                break;
            case R.id.zczt_img:
                showPopupWindow(zczt_img);
                break;
        }

    }
    // 把数据转换成json格式。用于上传服务端
    private void mapList() {
        jsonlist = new HashMap<String,String>();
//        zcmc_bull.setText(data.zcmc);
//        zclx_bull.setText(data.zclx);

            jsonlist.put("zczt",zczt_bull_tv.getText().toString());
            jsonlist.put("zcsl",zcsl_bull.getText().toString());
            jsonlist.put("qkms",qkms_bull.getText().toString());
            jsonlist.put("dyjxs",data.ssjxs);
            jsonlist.put("dymendian",data.ssmendian);
            jsonlist.put("czdd",bull_address_tv.getText().toString());
            jsonlist.put("name",data.name);
            jsonlist.put("czzb",caozuozb);
            jsonlist.put("czsj",datax);

            //营销资产id
            jsonlist.put("yxzc",data.id);
            System.out.println(jsonlist);
    }
    public void showPopupWindow(View v) {
        View contentView = View.inflate(this, R.layout.popup_role, null);
        final PopupWindow popupWindow = new PopupWindow(contentView,
                LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT, true);
        ListView popList = (ListView) contentView.findViewById(R.id.popList);
        popupWindow.setTouchable(true);
        // 如果不设置PopupWindow的背景，无论是点击外部区域还是Back键都无法dismiss弹框
        // 我觉得这里是API的一个bug
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        setShowListView(popList, popupWindow);
        // 设置好参数之后再show
        if (android.os.Build.VERSION.SDK_INT >=24) {
            int[] a = new int[2];
            v.getLocationInWindow(a);
            popupWindow.showAtLocation(getWindow().getDecorView(), Gravity.NO_GRAVITY, 0 , a[1]+v.getHeight());
        } else{
            popupWindow.showAsDropDown(v);
        }
//        popupWindow.showAsDropDown(v);
    }
    public void setShowListView(ListView popList, PopupWindow popupWindow) {
        mListx = new ArrayList<String>();
        mListx.add("正常");
        mListx.add("限期整改");
        mListx.add("损毁");
        mAdapter = new CommonListAdapter(mContext, mListx);
        popList.setAdapter(mAdapter);
        setPopListnener(popList, popupWindow);
    }

    public void setPopListnener(ListView popList, final PopupWindow popupWindow) {
        popList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                popupWindow.dismiss();
                zczt_bull_tv.setText(mListx.get(position).toString());
            }
        });}

    @Override
    public void register() {
        EventEngine.register(this);
    }

    @Override
    public void unRegister() {
        EventEngine.uregister(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unRegister();
        LocationManager.getInstance().unregisterlistener(mListener);
    }

    /**
     * 计算两点之间距离
     *
     * @return 米
     */
    private double getDistance_km(LatLng mudilng, LatLng melng) {

        double distanse = DistanceUtil.getDistance(mudilng, melng);
        distanse = Math.floor(distanse);

        //转换成公里
//        if (distanse < 1000) {
//        } else {
//            temp = String.format("%.2f", (distanse) / 1000) + "km";
//        }
        if(distanse>=500) {
            wubai = true;
        }else {
            wubai = false;
        }
        return distanse;
    }
    private BDLocation lastDBLocation;
    private BDLocationListener mListener = new BDLocationListener() {
        @Override
        public void onReceiveLocation(BDLocation location) {
            if (null != location
                    && location.getLocType() != BDLocation.TypeServerError) {
                if("4.9E-324".equals(String.valueOf(location.getLatitude()))){
                    if ("en".equals(mEns)) {
                        showToast("The location failed. Check that the location permission is open");
                    } else {
                        showToast("定位失败，请查看位置权限是否打开");
                    }
                    LocationManager.getInstance().stopRequestLocal();
                }
                lastDBLocation = location;
                LocationManager.getInstance().stopRequestLocal();
                LocationManager.log(lastDBLocation);
                refreshTvAddress();

                LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
                String zuobiao = data.tfzb;
                caozuozb = location.getLongitude()+","+location.getLatitude();
                double weidu =Double.valueOf(zuobiao.substring(0,zuobiao.indexOf(","))).doubleValue();
                double jingdu = Double.valueOf(zuobiao.substring(zuobiao.indexOf(",")+1,zuobiao.length())).doubleValue();
                tolatLng = new LatLng(jingdu,weidu);
                getDistance_km(latLng,tolatLng);
                if(isSave) {
                    dismissWainting();
                    mapList();
                    sendDate();
                    isSave = false;
                }

            } else {
                if (null != location) {
                    if ("en".equals(mEns)) {
                        showToast("Location failed, please try again!:" + location.getLocType());
                    } else {
                        showToast("定位失败，请重试! 错误码:" + location.getLocType());
                    }

                }
            }
        }
    };

    private void refreshTvAddress() {
        if (null != lastDBLocation) {
            bull_address_tv.setText(LocationManager.getDetailAddr(lastDBLocation,
                    false));
        } else {
            if ("en".equals(mEns)) {
                bull_address_tv.setText("Is positioning.....");
            } else {
                bull_address_tv.setText("正在定位.....");
            }

        }
    }
    public void takePhoto(int photo){
        String state = Environment.getExternalStorageState();
        if (state.equals(Environment.MEDIA_MOUNTED)) {
            File dir = new File(Environment.getExternalStorageDirectory() + "/"
                    + "CloudCC/photo/");
            if (!dir.exists())
                dir.mkdirs();
            imagename = Tools.getTimeName(System.currentTimeMillis());
            Intent intent = new Intent(
                    MediaStore.ACTION_IMAGE_CAPTURE);
            File f = new File(dir, imagename);// localTempImgDir和localTempImageFileName是自己定义的名字
            Uri u = Uri.fromFile(f);
            intent.putExtra(MediaStore.Images.Media.ORIENTATION, 0);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, u);
            startActivityForResult(intent,photo);
        } else {
            Tools.showInfo(mContext, "请插入SD卡");
        }
    }
    private String shuiyin(String imageurl) {
        // 将图片加上水印
        Bitmap sourBitmap = ImageUtil.getDiskBitmap(imageurl);
        String name = "By"
                + UserManager.getManager().getUser().userName;
        String time = Tools.getTime2(System.currentTimeMillis());

//                String address = currentLoc.getAddress();
        String address = bull_address_tv.getText().toString();
        // Bitmap fugai =
        // BitmapFactory.decodeResource(getResources(), R.id.a);
        String address1 = null;
        String address2 = null;
        Bitmap textBitmap = ImageUtil.drawTextToLeftBottom(this,
                sourBitmap, name, 100, Color.WHITE, 20, 130);
        textBitmap = ImageUtil.drawTextToLeftBottom(this,
                textBitmap, time, 100, Color.WHITE, 20, 100);
        textBitmap = ImageUtil.drawTextToLeftBottom(this,
                textBitmap, "", 40, Color.WHITE, 20, 85);
        if (address.length() > 20) {
            address1 = address.substring(0, 20);
            address2 = address.substring(11, address.length());
            textBitmap = ImageUtil.drawTextToLeftBottom(this,
                    textBitmap, address1, 100, Color.WHITE, 20, 70);
            textBitmap = ImageUtil.drawTextToLeftBottom(this,
                    textBitmap, address2, 100, Color.WHITE, 20, 40);

        } else {
            textBitmap = ImageUtil.drawTextToLeftBottom(this,
                    textBitmap, address, 100, Color.WHITE, 20, 30);
        }

        // 存储图片
        savePhotoToSDCard(Environment.getExternalStorageDirectory()
                        + "/" + "CloudCC" + "/photo", imagename + ".jpg",
                textBitmap);

        imageurl = Environment.getExternalStorageDirectory() + "/"
                + "CloudCC" + "/photo/" + imagename + ".jpg";
        return imageurl;
    }
    public void savePhotoToSDCard(String path, String photoname, Bitmap pBitmap) {
        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            String state = Environment.getExternalStorageState();
            if (state.equals(Environment.MEDIA_MOUNTED)) {
                File dir = new File(path);
                if (!dir.exists())
                    dir.mkdirs();
                File photoFile = new File(path, photoname);
                FileOutputStream fileOutputStream = null;
                try {
                    fileOutputStream = new FileOutputStream(photoFile);
                    if (pBitmap != null) {
                        if (pBitmap.compress(Bitmap.CompressFormat.JPEG, 100,
                                fileOutputStream)) {
                            fileOutputStream.flush();
                            fileOutputStream.close();
                        }
                    }
                } catch (Exception e) {
                    // TODO: handle exception
                } finally {
                    try {
                        fileOutputStream.close();
                    } catch (Exception e2) {
                        // TODO: handle exception
                    }
                }
            }
        }
    }
}
